﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;


namespace BusinessDll
{
    public class SocketServer
    {
        private string _ip = string.Empty;
        private int _port = 0;
        private Socket _socket = null;
        private byte[] buffer = new byte[1024 * 1024 * 2];
        public String _result = "";
        public bool isListen = true;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ip">监听的IP</param>
        /// <param name="port">监听的端口</param>
        public SocketServer(string ip, int port)
        {
            this._ip = ip;
            this._port = port;
        }
        public SocketServer(int port)
        {
            this._ip = "0.0.0.0";
            this._port = port;
        }

        public void StartListen()
        {
            try
            {
                if (_socket != null)
                {
                    WriteLog.WriteLogs("日志", "已经有了连接");
                    return;
                }
                WriteLog.WriteLogs("日志", "建立新连接");
                //实例化套接字(IP4寻找协议,流式协议,TCP协议)
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //创建IP对象
                IPAddress address = IPAddress.Parse(_ip);
                //创建网络端口,包括ip和端口
                IPEndPoint endPoint = new IPEndPoint(address, _port);
                //绑定套接字
                _socket.Bind(endPoint);
                //设置最大连接数
                _socket.Listen(int.MaxValue);

                //_socket.Accept();
                WriteLog.WriteLogs("日志", "监听" + _socket.LocalEndPoint.ToString() + "成功");
                Console.WriteLine("监听{0}成功", _socket.LocalEndPoint.ToString());
                //开始监听
                isListen = true;
                Thread thread = new Thread(ListenClientConnect);
                thread.Start();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                ex.ToString();
            }
        }

        /// <summary>
        /// 监听客户端连接
        /// </summary>
        private void ListenClientConnect()
        {
            Socket clientSocket = null;
            CommandList commandList = GlobalInfo.Instance.commandList;
            while (true)
            {
                if (!isListen)
                {
                    break;
                }
                try
                {
                    //Socket创建的新连接
                    clientSocket = _socket.Accept();
                    Dictionary<string, object> recv = new Dictionary<string, object>();
                    LineData lineData = new LineData();
                    int length = clientSocket.Receive(buffer);
                    WriteLog.WriteLogs("socket", "接收客户端:" + clientSocket.RemoteEndPoint.ToString() + "消息:" + Encoding.UTF8.GetString(buffer, 0, length));
                    String f = Encoding.UTF8.GetString(buffer, 0, length);

                    String[] arr = f.Split('&');
                    string content = "";
                    lineData.command = Command.operation;
                    if (arr != null && arr[0] != null && arr[0].Length > 0)
                    {
                        //todo 实际执行
                        lineData.body = recv;
                        commandList.pushCommandLine(lineData);
                    }
                    Console.WriteLine(content);
                    byte[] bytes = Encoding.Default.GetBytes(content);
                    clientSocket.Send(bytes);
                    clientSocket.Shutdown(SocketShutdown.Both);
                    //clientSocket.Close();
                    Thread.Sleep(100);
                }
                catch (Exception ex)
                {
                    WriteLog.printException(ex);
                }
                finally
                {
                    if (clientSocket != null)
                    {
                        //clientSocket.Shutdown(SocketShutdown.Both);
                        clientSocket.Close();
                        clientSocket = null;
                    }
                }
                Thread.Sleep(200);


            }

        }

        /// <summary>
        /// 监听客户端连接
        /// </summary>
        public void stop()
        {
            isListen = false;
            if (null != _socket)
            {
                WriteLog.WriteLogs("日志", "关闭连接");
                _socket.Close();
                _socket = null;
            }
        }

    }
}